package cn.tedu.egweibo0416.controller;

import cn.tedu.egweibo0416.base.response.JsonResult;
import cn.tedu.egweibo0416.base.response.StatusCode;
import cn.tedu.egweibo0416.mapper.CommentMapper;
import cn.tedu.egweibo0416.pojo.dto.CommentAddParam;
import cn.tedu.egweibo0416.pojo.entity.Comment;
import cn.tedu.egweibo0416.pojo.vo.CommentVO;
import cn.tedu.egweibo0416.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Api(tags = "评论模块")
@Slf4j
@RestController
@RequestMapping("/v1/comment/")
public class CommentController {
    @Autowired
    private CommentMapper commentMapper;
    @PostMapping("insert")
    @ApiOperation("发表评论功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insertComment(@RequestBody CommentAddParam commentAddParam, @ApiIgnore HttpSession session){
        log.debug("开始发表评论：");
        UserVO  userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddParam,comment);
        comment.setUserId(userVO.getId());
        comment.setCreateTime(new Date());
        int num = commentMapper.insertComment(comment);
        if (num > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
    @GetMapping("selectByWeiboId")
    @ApiOperation("查询微博评论列表")
    @ApiOperationSupport(order = 20)
    public JsonResult selectByWeiboId(@Range(min = 1,max = 100,message = "id必须在1~100之间") @RequestParam Long id,
                                      @ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        List<CommentVO> commentList = commentMapper.selectByWeiboId(id);
        if (commentList == null || commentList.isEmpty()){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok(commentList);
    }
}
